package com.xinyue.game.logic.frame.channel;

import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import com.mygame.common.concurrent.GameEventExecutorGroup;
import io.netty.util.concurrent.EventExecutor;

public class GameChannelGroup {

	private Map<Object, GameChannel> gameChannelMap = new HashMap<>();
	private EventExecutor executor;
	private GameEventExecutorGroup executorGroup;
	
	private ApplicationContext springContext;
	
	private static Logger logger = LoggerFactory.getLogger(GameChannelGroup.class);

	public GameChannelGroup(GameEventExecutorGroup executorGroup,ApplicationContext springContext) {
		this.executor = executorGroup.select(0);
		this.executorGroup = executorGroup;
		this.springContext = springContext;
	}

	private void executeTask(Runnable task) {
		this.executor.execute(() -> {
			try {
				task.run();
			} catch (Throwable e) {
				logger.error("执行任务失败", e);
			}
		});
	}

	public void gameChannelConsumer(Object key, Consumer<GameChannel> consumer) {
		this.executeTask(() -> {
			GameChannel gameChannel = this.gameChannelMap.get(key);
			if (gameChannel != null) {
				consumer.accept(gameChannel);
			} else {
				logger.debug("不存在{} 对应的GameChannel，创建新的GameChannel", key);
				
				gameChannel = new GameChannel(springContext,executorGroup.select(key), key.toString());
				this.gameChannelMap.put(key, gameChannel);
				consumer.accept(gameChannel);
			}
		});
	}
	

	public void removeGameChannel(Object key) {
		this.executeTask(() -> {
			gameChannelMap.remove(key);
		});
	}

}
